from repository.SQLiteDatabase import SQLiteDatabase
import json


class FeatureRepository:
    def __init__(self):
        with open("config.json", "r") as file:
            config = json.load(file)
        self.db = SQLiteDatabase(config["database"]["dbName"])

    def addFeature(self, featureDO):
        tar = featureDO.DO2Dict()
        tar.pop("id")
        return self.db.insert_data("sample_info", tar)

    def queryfamLableSum(self):
        return self.db.runSql(
            "select count(distinct fam_label) from sample_info where fam_label is not null"
        )

    def queryFamLabelTop10(self):
        return self.db.runSql(
            "SELECT fam_label, COUNT(*) AS label_count FROM sample_info WHERE fam_label IS NOT NULL GROUP BY fam_label ORDER BY label_count DESC LIMIT 10;"
        )

    def queryFeatureByMd5(self, md5Value, limit=None, offset=None):
        return self.db.select_data(
            "sample_info", "md5 = '{}'".format(md5Value), limit, offset
        )

    def queryEmbeddingByMd5(self, md5Value, limit=None, offset=None):
        tar = self.db.select_data(
            "sample_info", "md5 = '{}'".format(md5Value), limit, offset
        )
        res = (tar[0][1], tar[0][3])
        print("查询的特征结果为：")
        print(res)
        return res

    def queryAllEmbedding(self, limit=None, offset=None):
        tar = self.db.select_data("sample_info")
        print("共查询了{}条数据".format(len(tar)))
        res = []
        for data in tar:
            res.append((data[1], data[3]))
        # print("查询的特征结果为：")
        # print(res)
        return res

    def delFeature(self):
        pass

    def close(self):
        self.db.close()
